/**
 * Copyright @ 2000 ysten Co. Ltd. 
 * All right reserved.     
 * @author: wangmin
 * date: 2016-07-12     
 */
package com.task.controller;

import com.google.common.collect.Lists;
import com.task.bean.Constants;
import com.task.entity.Store;
import com.task.service.IStoreService;
import com.task.utils.JsonUtils;
import com.task.utils.RenderUtil;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 门店信息控制器
 */
@Controller
@RequestMapping("/web")
public class StoreController {

    private static final Logger LOGGER = LoggerFactory.getLogger(StoreController.class);

    @Autowired
    IStoreService storeService;

    @ResponseBody
    @RequestMapping(value = "/findStorePage.json")
    public JSONObject findStorePage(
            @RequestParam(value = "page", defaultValue = Constants.DEFAULT_PAGE) int pageNum,
            @RequestParam(value = "rows", defaultValue = Constants.DEFAULT_ROWS) int rows, ServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        try {
            Map<String, Object> searchParams = WebUtils.getParametersStartingWith(request, Constants.SEARCH_PREFIX);
            Page<Store> page = storeService.findStorePage(searchParams, pageNum, rows);
            if (page != null) {
                jsonObject.put(Constants.ROWS, page.getContent());
                jsonObject.put(Constants.TOTAL, page.getTotalElements());
            }
        } catch (Exception e) {
            LOGGER.error(" findStorePage page error:{}", e);
        }
        return jsonObject;
    }

    @ResponseBody
    @RequestMapping(value = "/getAllStore.json")
    public String findStorePage(ServletRequest request) {
        String json = "";
        try {
            Map<String, Object> searchParams = WebUtils.getParametersStartingWith(request, Constants.SEARCH_PREFIX);
            List<Store> page = storeService.findAll();
            if (page != null) {
                json = JsonUtils.toJson(page);
            }
        } catch (Exception e) {
            LOGGER.error(" findStorePage page error:{}", e);
        }
        return json;
    }

    @RequestMapping(value = "/toUploadStoreInfo")
    public String uploadStoreInfo(ServletRequest request) {
        return "/task/upload_strore_info";
    }

    @RequestMapping(value = "/uploadStoreInfo.json", method = RequestMethod.POST)
    public void uploadStoreInfo(MultipartHttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, MultipartFile> fileMap = request.getFileMap();
            String ctxPath = request.getSession().getServletContext().getRealPath(File.separator) + "\\excel\\";
            LOGGER.info("upload() ctxPath = " + ctxPath);

            // 创建文件夹
            File file = new File(ctxPath);
            if (!file.exists()) {
                if (file.mkdirs()) {
                    LOGGER.debug("upload() 创建文件夹成功 ");
                } else {
                    LOGGER.debug("upload() 创建文件夹失败 ");
                }
            }
            String fileName = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;

                File uploadFile = new File(ctxPath + newFileName);

                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                // 对读取Excel表格内容测试
                Map<Integer, String> map = ExcelReader.readExcel(ctxPath + newFileName);
                String info;
                String[] infoArr;
                List<Store> storeList = Lists.newArrayList();
                for (Integer key : map.keySet()) {
                    info = map.get(key);
                    if (StringUtils.isNotBlank(info)) {
                        infoArr = StringUtils.split(info,",");
                        if (infoArr != null && infoArr.length == 5) {
                            Store store = new Store();
                            store.setStoreCode(infoArr[0]);
                            store.setStoreName(infoArr[1]);
                            store.setStoreAddress(infoArr[2]);
                            store.setLatitude(Float.parseFloat(infoArr[3]));
                            store.setLongitude(Float.parseFloat(infoArr[4]));
                            storeList.add(store);
                        }
                    }
                    LOGGER.info(map.get(key));
                }
                if (!CollectionUtils.isEmpty(storeList)) {
                    storeService.saveOrUpdateStoreInfo(storeList);
                }
            }
            RenderUtil.renderText(Constants.SUCCESS,response);
        } catch (Exception e) {
            RenderUtil.renderText(Constants.FAIL,response);
            LOGGER.error("import excel error {}", e);
        }
    }
}
